<section class="content-header">
  <h1>&nbsp;</h1>
  <ol class="breadcrumb">
    <li><a><i class="fa fa-dashboard"></i>信息管理</a></li>
    <li class="active"><a>SIM卡管理</a></li>
  </ol>
</section>
<!-- Main content -->
<section class="content" id="deviceContent">
  <div class="row">
    <div class="col-xs-12">
      <div class="box">
        <div class="box-body">
			<!-- 搜索条件 -->
			<table class="table" style="border:1px sold red">
				<tr height="45px" bgcolor="#F3F3F3">
					<td align="left" style="width:150px;">
						<select class="form-control" id="sel_status">
							<option value="all">全部</option>
							<option value="0">未启用</option>
							<option value="1">已启用</option>
						</select>
					</td>
				    <td align="left" style="width:150px;">
						<select class="form-control" id="sel_install">
							<option value="all">全部</option>
							<option value="0">未安装</option>
							<option value="1">已安装</option>
						</select>
					</td>
					<td style="width:230px;">
						<input type="text" id="sel_company" class="form-control" placeholder="选择公司" onclick="$('#treeview').show()" value=""/>
					</td>
				    <td align="left" style="width:250px;">
				        <div class="input-group">
				          <input type="text" id="sel_sim_card" class="form-control" placeholder="SIM卡号">
				              <span class="input-group-btn">
				                <button id="searchBtn" name="searchBtn" id="search-btn" class="btn btn-flat" onClick=><i class="fa fa-search"></i></button>
				              </span>
				        </div>
					</td>
					<td align="left">
						<input type="button" class="btn btn-danger btn-small" value="添加" onclick="showDialog('insert','-1','-1');"/>&nbsp;
					</td>
				</tr>
			</table>
			<!-- 结果列表 -->
			<table id="myTableData" class="table table-bordered table-condensed table-hover table-striped">
             <thead>
             <tr>
			   <th>ID</th>
               <th width="50">序号</th>
               <th>SIM卡号</th>
               <th>车牌号</th>
               <th>设备号</th>
               <th>状态</th>
               <th>登记时间</th>
               <th>所属公司</th>
               <th>安装情况</th>
               <th>操作</th>                                 
             </tr>
             </thead>
             <tbody>
              </tbody>
            </table>
         	</div>
       	 </div>
      </div>
   </div>
</section>
<div class="modal fade" id="infoModal">
  <div class="modal-dialog" style="width:800px">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="infoModalTitle"></h4>
      </div>
      <div class="modal-body">
        <form class="form-horizontal" id="defaultForm">
			<div class="box-body">
              <table style="width:100%;">
              	<tr>
              		<td>
              			<div class="form-group">
              			  <label class="col-sm-3 control-label">SIM卡号</label>
		                  <div class="col-sm-6">
		                    <input type="text" class="form-control" id="sim_card" name="sim_card" maxlength="50"/>
		                  </div>
	                	</div>
               		</td>
              		<td>
              			<div class="form-group">
	                  	<label class="col-sm-3 control-label">所属公司</label>
	                  	<div class="col-sm-6">
	                    	<input type="text" class="form-control" id="company_name" name="company_name" onclick="showMenu();" placeholder="选择公司" readonly="true"/>
							<input type="hidden" id="company_id"/>
							<div id="menuContent" class="menuContent" style="display:none;position: absolute;z-index:999">
								<ul id="treeDemo" class="ztree"	style="margin-top:0; width:70%;min-height: 215px;overflow:auto;"></ul>
							</div>
	                   </div>
	                </div>	                		
              		</td>
              	</tr>
              	<tr>
					<td>
            			<div class="form-group">
            			  <label class="col-sm-3 control-label">登记时间</label>
                 		  <div class="col-sm-6">
                             <input type="text" class="form-control" id="registration_time"  name="registration_time" data-format="yyyy-mm-dd hh:mm:ss" >
                       	  </div>
                       </div>
              		</td>		                	
            		<td>
            			<div class="form-group">
            			    <label class="col-sm-3 control-label">启用状态</label>
			                <div class="col-sm-6">
			                    <select class="form-control" id="status">
									<option value="0">未启用</option>
									<option value="1">已启用</option>
								</select>
			                 </div>
                       </div>
              		</td>
                </tr>
               	<tr>
               		<td>
               			<div class="form-group">
               			  <label for="account" class="col-sm-3 control-label">备注</label>
		                  <div class="col-sm-9">
		                    <textarea class="form-control" rows="8" cols="50" maxlength="500" id="remark"></textarea>
		                  </div>
		                </div>
                 	</td>
                 	<td>&nbsp;</td>
               	</tr>		                		                			                
              </table>
       		</div>
             <div class="box-footer">
             	<div class="pull-right">
             		<input type="hidden" id="infoId"/>
              		<button type="button" class="btn btn-info" id="saveInfoBtn" >保存</button>
                 	&nbsp;&nbsp;&nbsp;&nbsp;
                	<button type="button" class="btn btn-default pull-right" data-dismiss="modal">关闭</button>
             	</div>
             </div>
          </form>
      </div>
    </div>
  </div>
</div>
<script type="text/javascript">
	$(function(){ 
    	 $("#registration_time").datetimepicker({
			defaultDate : new Date(),
			format : "YYYY-MM-DD HH:mm:ss"
		 }).on('dp.change', function(e) {
			if (!e.oldDate || e.oldDate == e.date)
				return;
			$("#registration_time").data("DateTimePicker").maxDate(e.date);
		 });
		 $("#myTableData").dataTable({
			  lengthMenu: [10],//这里也可以设置分页，但是不能设置具体内容，只能是一维或二维数组的方式，所以推荐下面language里面的写法。
		      paging: true,//分页
		      ordering: true,//是否启用排序
		      searching: false,//搜索
		      language: {
		    	  lengthMenu: '',//左上角的分页大小显示。
		          paginate: {//分页的样式内容。
		              previous: "上一页",
		              next: "下一页",
		              first: "首页",
		              last: "末页"
		          },
		          zeroRecords: "没有内容",//table tbody内容为空时，tbody的内容。
		          //下面三者构成了总体的左下角的内容。
		          info: "总共_PAGES_ 页，显示第_START_ 到第 _END_条记录 ，记录总数： _TOTAL_条 ",//左下角的信息显示，大写的词为关键字。
		          infoEmpty: "0条记录",//筛选为空时左下角的显示。
		          infoFiltered: ""//筛选之后的左下角筛选提示，
		      },
		      pagingType: "full_numbers",//分页样式的类型
		      "serverSide": true,
		      ajax: function (data, callback, settings) {
		           //封装请求参数
		           var param = {};
		           param.limit = data.length;//页面显示记录条数，在页面显示每页显示多少项的时候
		           param.start = data.start;//开始的记录序号
		           param.page = (data.start / data.length)+1;//当前页码
		           param.orderby=data.orderBys;
		           //ajax请求数据
		           $.ajax({
		               type: "post",
		               url: "${request.contextPath}/sim/searchList",
		               cache: false,  //禁用缓存
		               data: param,  //传入组装的参数
		               dataType: "json",
		               success: function (result) {
		                   //封装返回数据
		                   var returnData = {};
		                   returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
		                   returnData.recordsTotal = result.total;//返回数据全部记录
		                   returnData.recordsFiltered = result.total;//后台不实现过滤功能，每次查询均视作全部结果
		                   returnData.data = result.pageData;//返回的数据列表
		                   callback(returnData);
		               }
		           });
		       },
		       //列表表头字段
		       columns: [
		           { "data": "id" },
                   { "data": null},
		           { "data": "sim_card_substr" },
		           { "data": "vehid" },
		           { "data": "device_id" },
		           { "data": "status_name" },
		           { "data": "registration_time_str" },
		           { "data": "company_name" },
		           { "data": "install_name" },
		           { "data": null}
		       ],
             fnDrawCallback  : function(){
                 this.api().column(1).nodes().each(function(cell, i) {
                     cell.innerHTML =  i + 1;
                 });
             },
		       "aoColumnDefs":[
                   {
                       "targets":0,
                       "visible":false
                   },
		           {//倒数第一列
		               "targets":-1,
		               "bSortable": false,
		               render: function(data, type, row) {
		                   var html = '<button class="btn btn-success btn-small" onclick="showDialog(\'update\',\''+data.id+'\',\''+data.install+'\');">编辑</button>&nbsp;&nbsp;&nbsp;&nbsp;';
		                   if(data.install==0){//未安装
		                	  html += '<button class="btn btn-danger btn-small" onclick="deleteInfoInList(\''+data.id+'\');">删除</button>';
		                   }
		                   if(data.install==1){//已安装
		                	  html += '<button class="btn btn-default btn-small" disabled="disabled">删除</button>';
		                   }
		                   return html;
		               }
		           },
		        ]
		   });
	  $('#defaultForm').bootstrapValidator({
	        message: '此值无效',
	        feedbackIcons: {
	            valid: 'glyphicon glyphicon-ok',
	            invalid: 'glyphicon glyphicon-remove',
	            validating: 'glyphicon glyphicon-refresh'
	        },
	        fields: {
	        	sim_card: {
	                validators: {
	                    notEmpty: {
	                        message: '不能为空'
	                    }
	                }
	            },
	            company_name: {
	                validators: {
	                    notEmpty: {
	                        message: '不能为空'
	                    }
	                }
	            }
	        }
	    });
	   
	    $("#saveInfoBtn").on("click", function(){
		    var bootstrapValidator = $('#defaultForm').data('bootstrapValidator');
	        bootstrapValidator.validate();
	        if(bootstrapValidator.isValid()){
	            saveInfo();
	        }
		 });		 
		 onLoadCompanyTree();
	});
   function showDialog(opStr, id, installFlag){
	   $("#infoId").val(id);
	   $("#sim_card").removeAttr("disabled");
	   $("#company_id").removeAttr("disabled");
	   $("#company_name").removeAttr("disabled");
	   $("#status").removeAttr("disabled");
	   if(opStr=="insert"){
		   $("#infoModalTitle").text("添加SIM卡信息");
	   }
	   if(opStr=="update"){
		   $("#infoModalTitle").text("编辑SIM卡信息");
		   $("#sim_card").attr("disabled","disabled");
		   if(installFlag==1){
			   $("#company_id").attr("disabled","disabled");
			   $("#company_name").attr("disabled","disabled");
			   $("#status").attr("disabled","disabled");
		   }
		   $("#company_name").removeAttr("onclick");
		   $("#company_name").attr("disabled","disabled");
	   }
	    $.ajax({
	        url: "${request.contextPath}/sim/showDetail",
	        type: "post",
	        async: false,
	        data: {id:id},
	        success: function (data) {
	        	if(data){
	            	data = eval(data);
	            	if(data.success && data.msg){
	            		var item = data.msg;
	            		if(id=="-1"){
	            			$("#sim_card").val("");
	            			$("#company_id").val("");
	            			$("#company_name").val("");
	            			$("#status").val("1");
	            		}else{
	            			$("#sim_card").val(item.sim_card);
	            			$("#company_id").val(item.company_id);
	            			$("#company_name").val(item.company_name);
	            			$("#status").val(item.status);
	            			$("#registration_time").val(item.registration_time_str);
	            		}
	            		$("#remark").text(item.remark);
	            		$("#infoModal").modal('show');
	            	}else{
	            		alert("数据出错!");
	            		return false;
	            	}
	            }
	        },
	        error: function () { }
	   });
   }
   function saveInfo(){
	    var sim_card = $.trim($("#sim_card").val());
	    var company_id = $.trim($("#company_id").val());
	    var registration_time = $.trim($("#registration_time").val());
		var status = $("#status").val();
		var remark = $.trim($("#remark").val());
	    var data = {id:$("#infoId").val(), sim_card:sim_card, company_id:company_id, registration_time:registration_time, status:status, remark:remark};
	    $.ajax({
	        url: "${request.contextPath}/sim/saveOrUpdateInfo",
	        type: "post",
	        async: false,
	        data: data,
	        success: function (data) {
	        	if(data){
	            	data = eval(data);
	            	if(data.success){
	            		location.reload();
	            	}else{
	            		alert(data.msg);
	            		$("#sim_card").focus();
	            		return false;
	            	}
	            }
	        },
	        error: function () { }
	    });
   }
   function deleteInfoInList(id){
	   if(id){
		   CvMsg.confirm("警告","数据删除后将无法还原！是否删除？",function(){
			   $.ajax({
				    url: "${request.contextPath}/sim/deleteInfo",
					type : "post",
					data : {id:id},
					success : function(data) {
						if (data.success) {
							location.reload();
						} else {
		            		alert("数据出错!");
		            		return false;
						}
					}
				}); 
		   });
	   }
   }
   function onLoadCompanyTree(){
	   $.ajax({
			url : "${request.contextPath}/user/getTreeOrg",
			type : "post",
			success : function(data) {
				if (data.success && data.other) {
				   var setting = {
				   		view: {
				   			dblClickExpand: true
				   		},
				   		data: {
				   			simpleData: {
				   				enable: true
				   			}
				   		},
				   		callback: {
				   			onClick: onClick
				   		}
				   	};
				   var treeData = formatTreeImage(data.other);
			       $.fn.zTree.init($("#treeDemo"), setting, treeData);
			       $.fn.zTree.getZTreeObj("treeDemo").expandAll(true);//展开
				}
			}
		});
   }
  	function onClick(e, treeId, treeNode) {
   		var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
   		nodes = zTree.getSelectedNodes(),
   		v = "";
   		pv = "";
   		nodes.sort(function compare(a,b){return a.id-b.id;});
   		for (var i=0, l=nodes.length; i<l; i++) {
   			v += nodes[i].name + ",";
   			pv += nodes[i].id + ",";
   		}
   		if (v.length > 0 ) v = v.substring(0, v.length-1);
   		$("#company_name").val(v);
   		
   		if (pv.length > 0 ) pv = pv.substring(0, pv.length-1);
   		$("#company_id").val(pv);
   		
   		//移除校验
   		$('#defaultForm').data('bootstrapValidator')
        .updateStatus('company_name', 'NOT_VALIDATED', null)
        .validateField('company_name');
   		
   		hideMenu();
   	}
  	function showMenu() {
   		var cityObj = $("#pid");
   		var cityOffset = $("#pid").offset();
   		$("#menuContent").slideDown("fast");
   		$("body").bind("mousedown", onBodyDown);
   	}
   	function hideMenu() {
   		$("#menuContent").fadeOut("fast");
   		$("body").unbind("mousedown", onBodyDown);
   	}
   	function onBodyDown(event) {
   		if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
   			hideMenu();
   		}
   	}
</script>
